import e from './examine.module.scss'
import Welcome from '../../components/Welcome';
import { Button, Space, Table, message } from 'antd';
import type { TableColumnsType } from 'antd';
import { useEffect, useState } from 'react';
import axios from 'axios';
import { Outlet, useNavigate } from 'react-router-dom';


interface DataListType {
    key?: React.Key,
    article_author_id: string,
    articleImg?: string,
    articleTitle?: string,
    articleType?: string
}

function ExamineArticle() {
    const navigate = useNavigate()

    /* ------------------------------- 请求未审核的文章数据 ------------------------------- */
    const [articleList, setArticleList] = useState<DataListType[]>([])
    const getArticleList = async () => {
        let { data } = await axios({
            method: 'get',
            url: 'http://localhost:8080/api/admin/getArticleList'
        })
        let result: DataListType[] = []
        data.data.forEach((item: any) => {
            console.log(item);

            result.push({
                key: item.article_id + '',
                article_author_id: item.article_author_id + '',
                articleImg: item.article_coverimg,
                articleTitle: item.article_title,
                articleType: item.type_name
            })
        })
        setArticleList(result)

    }
    useEffect(() => {
        getArticleList()
    }, [])

    /* --------------------------------- 待审核文章表格 -------------------------------- */
    const columns: TableColumnsType<DataListType> = [
        {
            title: '文章封面',
            key: 'articleImg',
            dataIndex: 'articleImg',
            render: (text: any, record: any, index: any) => {
                return <div className='table-course' style={{ width: '50px', height: '50px' }}>
                    <img style={{ width: '100%', height: '100%' }} src={record.articleImg} alt="" />
                </div>
            }
        },
        {
            title: '文章标题',
            key: 'articleTitle',
            dataIndex: 'articleTitle',
            render: (text: any, record: any, index: any) => {
                console.log(record);

                return <div onClick={toDetailsAction(record.key, record.article_author_id)}>{record.articleTitle}</div>
            }
        },
        {
            title: '文章类型',
            key: 'articleType',
            dataIndex: 'articleType',
        },
        {
            title: '操作',
            key: 'action',
            dataIndex: 'action',
            render: (text: any, record: any, index: any) => (
                <Space size="middle">
                    <Button onClick={singlePassAction(record.key, 1)}>通过</Button>
                    <Button onClick={singlePassAction(record.key, 2)}>驳回</Button>
                </Space>
            ),
        },
    ]

    /* ------------------------------ 点击进入详情页的处理函数 ------------------------------ */
    const toDetailsAction = (article_id: number, article_author_id: number) => () => {
        console.log(article_id);
        // navigate({ pathname: 'articleDetails', search: `article_id=${article_id}user_id=${article_author_id}` })
        // navigate({ pathname: 'articleDetails', search: { article_id: article_id, user_id: article_author_id } })

    }

    // 单个通过/驳回
    const singlePassAction = (article_id: string, status: number) => async () => {
        await axios({
            method: 'post',
            url: 'http://localhost:8080/api/admin/changeArticleStatus',
            data: {
                article_ids: [article_id],
                status
            }
        })
        getArticleList()
        messageApi.open({
            type: 'success',
            content: `${status == 1 ? '通过' : '驳回'}文章成功`,
        });
    }

    // 已经选择的行的key组成的数组
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState(false);
    // 全局提示
    const [messageApi, contextHolder] = message.useMessage();

    // 当setSelectedRowKeys数组内有元素时，点击按钮的处理函数(批量通过/驳回)
    const allPassAction = (status: number) => async () => {
        console.log(selectedRowKeys);
        setLoading(true);
        await axios({
            method: 'post',
            url: 'http://localhost:8080/api/admin/changeArticleStatus',
            data: {
                article_ids: [...selectedRowKeys],
                status
            }
        })
        setLoading(false)
        setSelectedRowKeys([])
        getArticleList()
        messageApi.open({
            type: 'success',
            content: `批量${status == 1 ? '通过' : '驳回'}文章成功`,
        });
    };

    const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
        // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    // 选择表格行的配置项
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    // 能否点击按钮的标识，当selectedRowKeys数组内没有元素时就不能点击
    const hasSelected = selectedRowKeys.length > 0;

    return (

        <div className={e.page}>
            {contextHolder}
            <div className={e.container}>
                <div className={e.welcome}>
                    <Welcome></Welcome>
                </div>
                <div className={e.content}>
                    <div className={e.btnGroup} style={{ marginBottom: 16 }}>
                        <Button type="primary" onClick={allPassAction(1)} disabled={!hasSelected} loading={loading}>
                            批量通过
                        </Button>
                        <Button type="primary" onClick={allPassAction(2)} disabled={!hasSelected} loading={loading}>
                            批量驳回
                        </Button>
                        <span style={{ marginLeft: 8 }}>
                            {hasSelected ? `选择了 ${selectedRowKeys.length} 项` : ''}
                        </span>
                    </div>
                    <Table rowSelection={rowSelection} columns={columns} dataSource={articleList} />
                </div>
            </div>
        </div>
    );
}

export default ExamineArticle;